package org.jaronsource.framework.tools.select2sql;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;


public class Parser {
	
	private static final String SQL_PATTERN = "INSERT INTO SYS_DICT (RECORD_ID, DICT_TYPE, DICT_KEY, DICT_VALUE0) VALUES (S_SYS_DICT.NEXTVAL, '${DICT_TYPE}', '${DICT_KEY}', '${DICT_VALUE}');";
	/**
	 * 
	 * @param html
	 * @param sqlPattern INSERT INTO SYS_DICT (RECORD_ID, DICT_TYPE, DICT_KEY, DICT_VALUE0) VALUES (S_SYS_DICT.NEXTVAL, '${DICT_TYPE}', '${DICT_KEY}', '${DICT_VALUE0}');
	 * @return
	 */
	public List<String> parse(String html, String sqlPattern, String dictType, String dictTypeDesc) {
		
		if (sqlPattern == null) sqlPattern = SQL_PATTERN;
		
		Pattern pattern = Pattern.compile("<((?i)OPTION) ((?i)value)=[\"\']?(\\w+)[\"\']?>(.*?)</((?i)OPTION)>");
		Matcher matcher = pattern.matcher( html );
		
		List<String> result = new ArrayList<String>();
		String sqlDictType = replace(sqlPattern, "KIND", dictType, dictTypeDesc);
		result.add( sqlDictType );
		
		while(matcher.find()) {
			String sql = replace(sqlPattern, dictType, matcher.group(3), matcher.group(4));
			result.add( sql );
	    }
		
		return result;
	}
	
	private String replace( String sqlPattern,
							String dictType,
							String dictKey,
							String dictValue ) {
		
		String result = sqlPattern;
		result = StringUtils.replace( result, "${DICT_TYPE}", dictType );
		result = StringUtils.replace( result, "${DICT_KEY}", dictKey );
		result = StringUtils.replace( result, "${DICT_VALUE}", dictValue );
		
		return result;
	}

}
